﻿#region 命名空间

using System;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;

using WinnerCMS.Common;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.BLL
{
    [ConfigurationElementType(typeof (CustomCallHandlerData))]
    public class LoggingHandler : ICallHandler
    {
        /// <summary>
        /// 构造函数，此构造函数是用于Attribute调用
        /// </summary>
        /// <param name="_event">消息</param>
        public LoggingHandler(string _event)
        {
            Event = _event;
        }

        /// <summary>
        /// 构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public LoggingHandler(NameValueCollection attributes)
        {
            Order = Convert.ToInt32(attributes["Order"]);
            Event = String.IsNullOrEmpty(attributes["Message"]) ? "" : attributes["Message"];
        }

        /// <summary>
        /// 实现ICallHandler.Invoke方法，用于对具体拦截方法做相应的处理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        //[DebuggerStepThrough]
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input == null) throw new ArgumentNullException("input");
            if (getNext == null) throw new ArgumentNullException("getNext");

            //调用具体方法
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                return result;
            }

            var res = result.ReturnValue as Result;
            if (res != null && res.Errors.Length > 0)
            {
                return result;
            }

            if (Event.Contains("@p") && input.Inputs.Count > 0 && input.Arguments.Count > 0)
            {
                TextTemplate temp = new TextTemplate
                {
                    Inputs = input.Inputs
                };
                temp.Convert(Event);

                temp.Params.ForEach(x => { Event = Event.Replace(x.Key, x.Value); });
            }
            else if (Event.Length == 0 && res != null && !res.LogMessage.IsNullOrEmpty())
            {
                Event = res.LogMessage;
            }

            //如果调用方法没有出现异常则记录操作日志

            Log logModel = new Log
            {
                Type = LogTypeManage.GetTypeName(input.Target.GetType()),
                Event = Event
            };

#if TEST
                logModel.UserName = "Admin";
#else
            var user = UserManage.Current;
            if (user == null)
                throw new Exception("用户未登录！");

            logModel.UserName = user.UserName;
#endif
            LogManage.Add(logModel);

            //返回方法，拦截结束
            return result;
        }

        public string Event { get; set; }


        public int Order { get; set; }
    }
}